<script lang="ts" setup>
import {  Plus } from '@vben/icons';
import { ElMessage } from 'element-plus';
import { ref, watch } from 'vue';

import { uploadAvatar } from '#/api/system/user';
import { $t } from '#/locales';

const props = defineProps({
  value: {
    type: String,
    default: '',
  },
  userId: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['update:value', 'success']);

const avatarUrl = ref(props.value || '');
const uploading = ref(false);

// 监听props变化
watch(
  () => props.value,
  (val) => {
    avatarUrl.value = val || '';
  }
);

// 上传头像前的验证
const beforeUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error($t('system.user.avatarFormatError'));
    return false;
  }
  if (!isLt2M) {
    ElMessage.error($t('system.user.avatarSizeError'));
    return false;
  }
  return true;
};

// 上传头像
const handleUpload = async (file: File) => {
  if (!beforeUpload(file)) {
    return;
  }

  try {
    uploading.value = true;

    const formData = new FormData();
    formData.append('file', file);
    if (props.userId) {
      formData.append('userId', props.userId);
    }

    const result = await uploadAvatar(formData);

    // 更新头像URL
    avatarUrl.value = result;
    emit('update:value', result);
    emit('success', result);

    ElMessage.success($t('system.user.avatarUploadSuccess'));
  } catch (error) {
    console.error('上传头像失败:', error);
    ElMessage.error($t('system.user.avatarUploadFailed'));
  } finally {
    uploading.value = false;
  }
};

// 点击上传按钮
const triggerUpload = () => {
  document.getElementById('avatar-upload-input')?.click();
};

// 文件选择变化
const handleFileChange = (event: Event) => {
  const fileInput = event.target as HTMLInputElement;
  const file = fileInput.files?.[0];
  if (file) {
    handleUpload(file);
  }
  // 重置input，允许选择相同文件时也能触发change事件
  fileInput.value = '';
};
</script>

<template>
  <div class="avatar-uploader">
    <div
      v-if="avatarUrl"
      class="avatar-wrapper"
      @click="triggerUpload"
    >
      <img :src="avatarUrl" class="avatar" />
      <div class="avatar-mask">
        <span>{{ $t('system.user.changeAvatar') }}</span>
      </div>
    </div>
    <div
      v-else
      class="avatar-placeholder"
      @click="triggerUpload"
    >
      <Plus class="plus-icon" />
      <span>{{ $t('system.user.uploadAvatar') }}</span>
    </div>

    <input
      id="avatar-upload-input"
      type="file"
      accept="image/jpeg,image/png,image/gif"
      style="display: none;"
      @change="handleFileChange"
    />

    <div class="avatar-tips text-muted text-xs mt-1">
      {{ $t('system.user.avatarTips') }}
    </div>
  </div>
</template>

<style scoped>
.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.avatar-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px dashed #d9d9d9;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-placeholder:hover {
  border-color: var(--el-color-primary);
}

.plus-icon {
  font-size: 24px;
  color: #8c8c8c;
}

.avatar-tips {
  margin-top: 4px;
  color: #999;
  font-size: 12px;
}
</style>
